package com.wcy.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wcy.annotation.aop.PreAuth;
import com.wcy.entity.LearningResource;
import com.wcy.entity.UserCollection;
import com.wcy.entity.queryVo.QueryConvertor;
import com.wcy.service.IUserCollectionService;
import com.wcy.util.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/userCollection")
public class UserCollectionController {

    @Autowired
    private IUserCollectionService userCollectionService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PreAuth("COLLECTION:QUERY")
    @GetMapping("/page")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Page<UserCollection>> getPage(@RequestParam(defaultValue = "1") int pageNum,
                                                        @RequestParam(defaultValue = "10") int pageSize,
                                                        HttpServletRequest request) {
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData).convert(true);
        Page<UserCollection> page = userCollectionService.page(new Page<>(pageNum, pageSize),wrapper);
        return ResponseEntity.ok(page);
    }

//    @PreAuth("COLLECTION:QUERY")
    @GetMapping("/list")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<List<UserCollection>> getList(HttpServletRequest request) {
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData).convert(true);
        List<UserCollection> list = userCollectionService.list(wrapper);
        return ResponseEntity.ok(list);
    }

    @PreAuth("COLLECTION:ADD")
    @PostMapping("/add")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> add(@RequestBody UserCollection userCollection) {
        userCollection.setCollectedAt(LocalDateTime.now());
        userCollectionService.save(userCollection);
        return ResponseEntity.ok().build();
    }

    @PreAuth("COLLECTION:ALTER")
    @PutMapping("/update")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> update(@RequestBody UserCollection userCollection) {
        userCollectionService.updateById(userCollection);
        return ResponseEntity.ok().build();
    }

    @PreAuth("COLLECTION:DELETE")
    @DeleteMapping("/delete/{id}")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> delete(@PathVariable Integer id) {
        userCollectionService.removeById(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/user/page")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Page<UserCollection>> getByUserId(@RequestParam(defaultValue = "1") int pageNum,
                                                        @RequestParam(defaultValue = "10") int pageSize,
                                                        HttpServletRequest request) {
        Integer userId = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData,true).convert(true);
        wrapper.eq("user_id",userId);
        Page<UserCollection> page = userCollectionService.page(new Page<>(pageNum, pageSize),wrapper);
        return ResponseEntity.ok(page);
    }

    @GetMapping("/user/{id}")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Boolean> hasCollection(@PathVariable("id") Integer id,HttpServletRequest request) {
        Integer userId = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        return ResponseEntity.ok(userCollectionService.exists(new QueryWrapper<UserCollection>().eq("user_id",userId).eq("resource_id", id)));
    }

    @DeleteMapping("/user/delete/{id}")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Boolean> deleteCollection(@PathVariable Integer id,HttpServletRequest request) {
        Integer userId = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        if (userCollectionService.exists(new QueryWrapper<UserCollection>().eq("user_id",userId).eq("resource_id", id))){
            userCollectionService.remove(new QueryWrapper<UserCollection>().eq("user_id",userId).eq("resource_id", id));
            return ResponseEntity.ok(true);
        }
        return ResponseEntity.ok(false);
    }

    @PostMapping("/user/add/{id}")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Boolean> addCollection(@PathVariable Integer id,HttpServletRequest request) {
        Integer userId = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        if (!userCollectionService.exists(new QueryWrapper<UserCollection>().eq("user_id",userId).eq("resource_id", id))){
            userCollectionService.save(new UserCollection().setUserId(userId).setResourceId(id).setCollectedAt(LocalDateTime.now()));
            return ResponseEntity.ok(true);
        }
        return ResponseEntity.ok(false);
    }
}